package com.axend.lib_base.base.activity

import androidx.activity.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.axend.lib_base.R
import com.axend.lib_base.ext.getVMCls
import com.axend.lib_base.base.vm.BaseViewModel
import com.axend.lib_base.bean.LoadAction
import com.axend.lib_base.utils.CommUtils
import com.axend.lib_base.utils.NetWorkUtil
import com.axend.lib_base.view.dialog.LoadingDialogManager

abstract class BaseVMActivity<VM : BaseViewModel> : AbsActivity() {
    protected lateinit var mViewModel: VM

    //使用这个方法简化ViewModel的获取
    protected inline fun <reified VM : BaseViewModel> getViewModel(): VM {
        val viewModel: VM by viewModels()
        return viewModel
    }

    //反射自动获取ViewModel实例
    protected open fun createViewModel(): VM {
        return ViewModelProvider(this).get(getVMCls(this))
    }

    override fun initViewModel() {
        mViewModel = createViewModel()
    }

    override fun startObserve() {
        //观察网络数据状态
        mViewModel.getActionLiveData().observe(this, stateObserver)
    }

    override fun setContentView() {
        setContentView(getLayoutIdRes())
    }

    abstract fun getLayoutIdRes(): Int

    override fun onNetworkConnectionChanged(
        isConnected: Boolean,
        networkType: NetWorkUtil.NetworkType?
    ) {
    }

    // ================== 网络状态的监听 ======================

    private var stateObserver: Observer<LoadAction> = Observer { loadAction ->
        when (loadAction.action) {
            LoadAction.STATE_NORMAL -> showStateNormal()
            LoadAction.STATE_ERROR -> showStateError(loadAction.message)
            LoadAction.STATE_SUCCESS -> showStateSuccess()
            LoadAction.STATE_LOADING -> showStateLoading("")
            LoadAction.STATE_NO_DATA -> showStateNoData()
            LoadAction.STATE_PROGRESS -> showStateProgress()
            LoadAction.STATE_HIDE_PROGRESS -> hideStateProgress()
            LoadAction.STATE_CALIBRATION -> showStateLoading(CommUtils.getString(R.string.app_tips_calibration_ing))
        }
    }

    protected open fun showStateNormal() {}

    protected open fun showStateError(message: String?) {
        LoadingDialogManager.get().dismissLoading()
    }

    protected open fun showStateSuccess() {
        LoadingDialogManager.get().dismissLoading()
    }

    protected open fun showStateLoading(content: String) {
        LoadingDialogManager.get().showLoading(this, content)
    }

    protected open fun showStateNoData() {
        LoadingDialogManager.get().dismissLoading()
    }

    protected fun showStateProgress() {
        LoadingDialogManager.get().showLoading(mActivity, "")
    }

    protected fun hideStateProgress() {
        LoadingDialogManager.get().dismissLoading()
    }


}